using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using PowerSearch.AppServices;
using PowerSearch.Core;
using System.Threading.Tasks;

namespace PowerSearch.ICS
{
	[Activity (Label = "Top Stories")]			
	public class ResultActivity : Activity
	{
		IList<Feed> _results;
		string _provider;

		protected override void OnCreate (Bundle bundle)
		{
			base.OnCreate (bundle);

			SetContentView (Resource.Layout.Result);

			_provider = Intent.GetStringExtra ("Provider");
			if (string.IsNullOrEmpty (_provider)) {
				StartActivity (typeof(MainActivity));
				return;
			}

			var txtProvider = FindViewById<TextView> (Resource.Id.txtProvider);
			txtProvider.Text = _provider;

			var btnBack = FindViewById<ImageButton> (Resource.Id.btnBack);
			btnBack.Click += (object sender, EventArgs e) => {
				StartActivity (typeof(MainActivity));
			};

			var btnRefresh = FindViewById<ImageButton> (Resource.Id.btnRefresh);
			btnRefresh.Click += (object sender, EventArgs e) => {
				LoadResults(_provider);
			};

			LoadResults(_provider);
		}

		private void LoadResults(string provider)
		{
			var progressBar = FindViewById<ProgressBar>(Resource.Id.progressBar1);
			progressBar.Visibility = ViewStates.Visible;

			Task.Factory.StartNew (() => GetResults(provider))
				.ContinueWith(task => {
					RunOnUiThread(()=> {
						progressBar.Visibility = ViewStates.Gone;

						var resultAdapter = new ResultAdapter (this, _provider, _results);
						var lstResult = FindViewById<ListView> (Resource.Id.lstResult);
						lstResult.Adapter = resultAdapter;
					});
				});	
		}

		private void GetResults(string provider)
		{
			var searchService = new SearchService ();
			_results = searchService.GetSearchResults (string.Empty, new string[] { provider});
		}
	}
}

